import { login, getUserInfo } from '@/api/user'
export default {
  namespaced: true,
  state: {
    token: localStorage.getItem('my_token'),
    userInfo: null
  },
  mutations: {
    // 设置token
    setToken(state, token) {
      localStorage.setItem('my_token', token)
      state.token = token
    },
    // 设置用户信息
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    // 退出登录
    logout(state) {
      // 移除token
      state.token = null
      //  移除用户信息
      state.userInfo = null
    }
  },
  actions: {
    async  login(context, data) {
      // 发起登录请求
      const res = await login(data)
      // 提交token
      context.commit('setToken', res.jwt)
    },
    // 获取用户信息
    async getUserInfo(context) {
      const res = await getUserInfo()
      context.commit('setUserInfo', res)
      return res
    },
    // 退出登录
    async logout(context) {
      context.commit('logout')
    }
  }
}
